package org.codehaus.activemq.message;

import java.io.ByteArrayOutputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public abstract class AbstractPacketWriter
  implements PacketWriter
{
  protected void writeUTF(String str, DataOutput dataOut)
    throws IOException
  {
    if (str == null) {
      str = "";
    }
    dataOut.writeUTF(str);
  }

  public boolean canWrite(Packet packet)
  {
    return packet.getPacketType() == getPacketType();
  }

  protected void writeObject(Object object, DataOutput dataOut)
    throws IOException
  {
    if (object != null) {
      ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
      ObjectOutputStream objOut = new ObjectOutputStream(bytesOut);
      objOut.writeObject(object);
      objOut.flush();
      byte[] data = bytesOut.toByteArray();
      dataOut.writeInt(data.length);
      dataOut.write(data);
    }
    else {
      dataOut.writeInt(0);
    }
  }

  public byte[] writePacketToByteArray(Packet packet)
    throws IOException
  {
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(bytesOut);
    writePacket(packet, dataOut);
    dataOut.flush();
    return bytesOut.toByteArray();
  }

  public void writePacket(Packet packet, DataOutput dataOut)
    throws IOException
  {
    writeUTF(packet.getId(), dataOut);
    dataOut.writeBoolean(packet.isReceiptRequired());
  }
}